<?php
namespace app\api\model;

use app\disk\controller\Dir;
use think\Model;
use think\Db;

/**
 * www.zhouchunyu.com.
 * Created on 2019/1/7 17:22
 * Created by One <admin@zhouchunyu.com>
 */

class User extends Model {

    static function login($email='', $password='') {
        $user = Db::name('users')->where('email',$email)->find();
        if(!$user) {
            error('用户名或密码错误',404);
        }else if($user['passwd'] !== getPassword($password,$user['salt'])) {
            error('用户名或密码错误',404);
        }else if($user['status'] == 0) {
            error('该用户未激活',403);
        }else if($user['status'] == -1) {
            error('用户不存在',403);
        }else if($user['status'] == 2) {
            error('该用户已被禁止登陆',403);
        }

        $time = time();
        $expires_in = 7200;
        $exp_time = $time + $expires_in;
        $UserData = data2Jwt([
            'uid' => $user['id'],
            'nickname' => $user['nickname'],
            'truename' => $user['truename'],
            'email' => $user['email'],
            'avatar' => $user['avatar'],
            'used_storage' => $user['used_storage'],
            'user_group' => $user['user_group'],
            'status' => $user['status'],
            'iat'=> $time,
            'expires_in'=> $expires_in,
//            'exp'=> $exp_time,
        ]);

        success([
            'token'=>$UserData,
            'refresh_token'=>data2Jwt(['uid'=>$user['id'],'expires_in'=>'604800','exp'=>$time+604800]),
            'expires_in'=>$expires_in,
            'exp_time'=>$exp_time,
            'nickname'=>$user['nickname'],
            'avatar'=>$user['avatar'],
            'used_storage'=>$user['used_storage']
        ]);

    }


    /**
     * @param string $email
     * @param string $password
     */
    static function register($email='', $password='', $nickname='') {
        if(Db::name('users')->where('email',$email)->find()) {
            error('改邮箱已被注册',408);
        }

        $salt = RandStr(16);

        $InsertData = [
            'nickname' => $email,
            'email' => $email,
            'passwd' => getPassword($password,$salt),
            'salt' => $salt,
            'ret_ip' => getIp(),
            'user_group' => getDbConfig('default_user_group'),
        ];
        if(Db::name('users')->insert($InsertData)) {
            $dirModel = new Dir();
            $dirModel->create('/');
            success([],'200','注册成功');
        }else{
            error('注册失败',500);
        }
        echo $salt;die;
    }

}